import time

from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from datetime import datetime, timedelta

from info import constants
from info import db
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import admin_blue


@admin_blue.route("/login", methods=["GET", "POST"])
def admin_login():
    if request.method == "GET":
        user_id = session.get("user_id", None)
        is_admin = session.get("is_admin", False)
        if user_id and is_admin:
            return redirect(url_for("admin.admin_index"))
        return render_template("admin/login.html")
    username = request.form.get("username")
    password = request.form.get("password")
    user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    if not user:
        return render_template("admin/login.html", errmsg="没有该管理员账户")
    if not user.check_password(password):
        return render_template("admin/login.html", errmsg="密码错误")
    session["user_id"] = user.id
    session["mobile"] = username
    session["nick_name"] = username
    session["is_admin"] = True
    # return render_template("admin/index.html")   # 这样登录成功会显示user undefined
    return redirect(url_for("admin.admin_index"))


@admin_blue.route("/index")
@user_login_data
def admin_index():
    user = g.user
    return render_template("admin/index.html", user=user.to_dict())


@admin_blue.route("/user_count")
def admin_user_count():
    total_count = 0
    mon_count = 0
    day_count = 0
    total_count = User.query.filter(User.is_admin == False).count()
    t = time.localtime()
    mon_begin = "%d‐%02d‐01" % (t.tm_year, t.tm_mon)
    mon_begin_date = datetime.strptime(mon_begin, '%Y‐%m‐%d')
    mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_date).count()
    t = time.localtime()
    day_begin = "%d‐%02d‐%02d" % (t.tm_year, t.tm_mon, t.tm_mday)
    day_begin_date = datetime.strptime(day_begin, '%Y‐%m‐%d')
    day_count = User.query.filter(User.is_admin == False, User.create_time >= day_begin_date).count()
    t = time.localtime()
    today_begin = "%d‐%02d‐%02d" % (t.tm_year, t.tm_mon, t.tm_mday)
    today_begin_date = datetime.strptime(today_begin, '%Y‐%m‐%d')
    active_count = []
    active_date = []
    for i in range(0, 30):
        begin_data = today_begin_date - timedelta(days=i)
        end_data = today_begin_date - timedelta(days=(i - 1))
        count = User.query.filter(User.create_time >= begin_data, User.create_time < end_data).count()
        active_count.append(count)
        active_date.append(begin_data.strftime('%Y‐%m‐%d'))
    active_count.reverse()
    active_date.reverse()
    data = {
        "active_time": active_date,
        "active_count": active_count,
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count
    }
    return render_template("admin/user_count.html", data=data)


@admin_blue.route("/user_list")
def user_list():
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        p = 1
    paginate = User.query.filter(User.is_admin == False).order_by(User.create_time.desc()).paginate(p, 10, False)
    items = paginate.items
    current_page = paginate.page
    total_page = paginate.pages
    users = []
    for user in items:
        users.append(user.to_admin_dict())
    data = {
        "users": users,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("admin/user_list.html", data=data)


@admin_blue.route("/news_review")
def news_review():
    p = request.args.get("p", 1)
    keywords = request.args.get("keywords")
    try:
        p = int(p)
    except Exception as e:
        p = 1
    filter = [News.status != 0]
    if keywords:
        filter.append(News.title.contains(keywords))
    paginate = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(p, 10, False)
    items = paginate.items
    current_page = paginate.page
    total_page = paginate.pages
    news_list = []
    for news in items:
        news_list.append(news.to_review_dict())
    data = {
        "news_list": news_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("admin/news_review.html", data=data)


@admin_blue.route("/news_review_detail", methods=["GET", "POST"])
def news_review_detail():
    if request.method == "GET":
        news_id = request.args.get("news_id")
        news = News.query.get(news_id)
        data = {
            "news": news.to_dict(),
        }
        return render_template("admin/news_review_detail.html", data=data)
    action = request.json.get("action")
    news_id = request.json.get("news_id")
    news = News.query.get(news_id)
    if action == "accept":
        news.status = 0
    else:
        reason = request.json.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="缺少参数")
        news.status = -1
        news.reason = reason
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="新闻审核成功")


@admin_blue.route("/news_edit")
def news_edit():
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        p = 1
    paginate = News.query.order_by(News.create_time.desc()).paginate(p, 10, False)
    items = paginate.items
    current_page = paginate.page
    total_page = paginate.pages
    news_list = []
    for news in items:
        news_list.append(news.to_review_dict())
    data = {
        "news_list": news_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("admin/news_edit.html", data=data)


@admin_blue.route("/news_edit_detail", methods=["GET", "POST"])
def news_edit_detail():
    if request.method == "GET":
        news_id = request.args.get("news_id")
        news = News.query.get(news_id)
        categories = Category.query.all()
        category_list = []
        for category in categories:
            category_list.append(category.to_dict())
        category_list.pop(0)
        data = {
            "news": news.to_dict(),
            "categories": category_list
        }
        return render_template("admin/news_edit_detail.html", data=data)
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")
    news_id = request.form.get("news_id")

    if not all([title, digest, content, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # news = None

    news = News.query.get(news_id)

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据")
    if index_image:
        try:
            index_image = index_image.read()
            key = storage(index_image)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="第三方系统错误")
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.title = title
    news.digest = digest
    news.content = content
    news.category_id = category_id
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="新闻编辑成功")


@admin_blue.route("/news_type")
def news_type():
    categories = Category.query.all()
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())
    category_list.pop(0)
    data = {
        "categories": category_list
    }
    return render_template("admin/news_type.html", data=data)


@admin_blue.route("/add_category",methods = ["GET","POST"])
def add_category():
    cid = request.json.get("id")
    name = request.json.get("name")
    if not name:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if cid:
        category = Category.query.get(cid)
        category.name = name
    else:
        category = Category()
        category.name = name
        db.session.add(category)
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="修改成功")

@admin_blue.route("/delete")
def delete():
    """从前端获取分类的category_id"""
    category_id = request.args.get("category_id")
    news_list = News.query.filter(News.category_id == category_id).all()
    if news_list:
        for news in news_list:
            db.session.delete(news)
            db.session.commit()
    category = Category.query.get(category_id)
    db.session.delete(category)
    db.session.commit()
    return redirect(url_for("admin.news_type"))


@admin_blue.route("/news_delete")
def news_delete():
    """从前端获取新闻的news_id"""
    news_id = request.args.get("news_id")
    news = News.query.get(news_id)
    if news:
        db.session.delete(news)
        db.session.commit()
    return redirect(url_for("admin.news_edit"))

@admin_blue.route("/user_logout")
def user_logout():
    session.pop("user_id")
    session.pop("nick_name")
    session.pop("mobile")
    session.pop("is_admin")
    return redirect("http://127.0.0.1:5000/admin/login")


